package work.javac.exec;

import work.javac.common.FileReadWriter;
import work.javac.common.Log;
import work.javac.common.PathUtil;
import work.javac.common.database.SQLExecute;
import work.javac.common.database.utils.DBUtils;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

public class Skewness {

    private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
    private static final String EOL = System.getProperty("line.separator");
    private static final String ALL = "skewness_all_";
    private static final String ERR = "skewness_err_";
    private static final String TYPE = ".log";
    private static StringBuffer all_log = new StringBuffer(100000);
    private static StringBuffer err_log = new StringBuffer(100000);

    public static void start(Map map) throws SQLException, IOException {
        Log.info("开始检查数据倾斜状态");
        String output = (String) map.get("output");
        String table = (String) map.get("table");
        if(output == null){
            Log.err("请检查参数(-o)数据源不能为空!");
            System.exit(1);
        }
        try (Connection conn = DBUtils.getConn(output)){
            List<String> skewness = SQLExecute.getSkewness(conn, table);
            all_log.append("数据量相差5%以上即可视为倾斜,如果相差10%以上就必须要调整分布列!");
            all_log.append(EOL);
            skewness.forEach(item -> {
                all_log.append(item);
                all_log.append(EOL);
                if(item.contains("可能存在数据倾斜")){
                    err_log.append(item);
                    err_log.append(EOL);
                }
            });
            LocalDateTime localDateTime = LocalDateTime.now();
            String path = PathUtil.getFile(ALL + localDateTime.format(formatter) + TYPE).getPath();
            FileReadWriter.writer(path, all_log.toString());
            Log.info("数据倾斜分析完毕!全部日志路径:%s", path);
            if(err_log.length() == 0){
                Log.info("没有异常日志!");
            }else{
                path = PathUtil.getFile(ERR + localDateTime.format(formatter) + TYPE).getPath();
                FileReadWriter.writer(path, err_log.toString());
                Log.info("数据倾斜分析完毕!异常日志路径:%s", path);
            }
        }
//        DBUtils.close(conn);
    }

}
